/* eslint-disable prettier/prettier */
// import RNFS from 'react-native-fs';
import CryptoJS from 'crypto-js';
import { WXstate } from '../enums/constant';
import RNFS from 'react-native-fs';

export interface WarmText {
    name: string;
    value: string;
  }
  
  export interface WarmTextArray {
    WarmTextArray: WarmText[];
  }

export interface NewWord {
    dictionary: string;
    wordPath: string;
    wordName: string;
    ChaiZi:string[];
}

interface Chapter {
    newWordList: NewWord[];
    directoryList: string[];
    chapterName: string;
}
interface Unit {
    chapterlist: Chapter[];
    unitname: string;
}

interface Book {
    unitlists: Unit[];
    bookName: string;
}

const location = `${WXstate.DOWNLOAD_LOCATION}`;
const GetjsonData = async (unitnames: string): Promise<string[]> => {
    console.log('dealing with json');
    try {
        // 加载 JSON 文件并自动解析为 JavaScript 对象
        const jsonObject: Book = require('../../android/app/src/main/res/grade_1_1_0.json');
        console.log(jsonObject);
        // 使用 TypeScript 类型守卫来找到匹配的单元
        let targetUnit = jsonObject.unitlists.find(Unit => Unit.unitname === unitnames);
        let resultArray: string[] = [];
        if (targetUnit) {
            let directoryList = targetUnit.chapterlist[0].directoryList;
            await Promise.all(directoryList.map(async (directory: string) => {
                let coode = encode(directory);
                let uri =  `${location}${coode}`;
                console.log(uri + '.zip' + '&&&&&&&&&&&&&&&&' );
               resultArray.push(coode);
                // 如果需要下载文件，取消下面代码的注释并配置 URL 和路径
                // const sourceUrl = `http://example.com/path/to/${directory}`;
                // const filePath = RNFS.DocumentDirectoryPath + '/' + directory;
                // await RNFS.downloadFile({ from: sourceUrl, to: filePath });
            }));
        } else {
            console.log('没有对应的学习内容资源！');
            resultArray = [];
        }
        return resultArray;
    } catch (error) {
        console.error(error);
        throw error; // 抛出错误，以便调用者可以处理
    }
};

export const GetjsonText = async (wordText: string): Promise<string> => {
    console.log('dealing with json');
    try {
        // 加载 JSON 文件并自动解析为 JavaScript 对象
        const jsonObject: WarmTextArray = require('../../android/app/src/main/res/grade_text.json');
        // 使用 TypeScript 类型守卫来找到匹配的单元
        let targetText = jsonObject.WarmTextArray.find(WarmText => WarmText.name === wordText);
        let result: string = '';
        if (targetText) {
              result = targetText.value;
        } else {
            console.log('没有对应的文本内容资源！');
            result = '';
        }
        return result;
    }
     catch (error) {
        console.error(error);
        throw error; // 抛出错误，以便调用者可以处理
    }
};

export const Getjsonwords = async (unitnames: string): Promise<NewWord[]> => {
    console.log('dealing with json');
    try {
        // 加载 JSON 文件并自动解析为 JavaScript 对象
        const jsonObject: Book = require('../../android/app/src/main/res/grade_1_1_0.json');
        // 使用 TypeScript 类型守卫来找到匹配的单元
        let targetUnit = jsonObject.unitlists.find(Unit => Unit.unitname === unitnames);
        let resultArray: NewWord[] = [];
        if (targetUnit) {
                let newWordList = targetUnit.chapterlist[0].newWordList;
                await Promise.all(newWordList.map(async (NewWord: NewWord) => {
                    let cooode =  NewWord;
                    console.log( cooode + '  orzorzorzorz' );
                   resultArray.push( cooode );
                }));
                // 如果需要下载文件，取消下面代码的注释并配置 URL 和路径
                // const sourceUrl = `http://example.com/path/to/${directory}`;
                // const filePath = RNFS.DocumentDirectoryPath + '/' + directory;
                // await RNFS.downloadFile({ from: sourceUrl, to: filePath });
        } else {
            console.log('没有对应的学习内容资源！');
            resultArray = [];
        }
        return resultArray;
    } catch (error) {
        console.error(error);
        throw error; // 抛出错误，以便调用者可以处理
    }
};
export const GetChaizi = async (word: NewWord): Promise<string[]> => {
    console.log('dealing with json');
    let resultArray: string[] = [];
    try {
        console.log(word);
        console.log(word.ChaiZi);
        let bushouList = word.ChaiZi;
        await Promise.all(bushouList.map(async (Bushou: string) => { 
            console.log(Bushou);
           resultArray.push( Bushou );
        }));
    } catch (error) {
        console.error(error);
        console.log('没有对应的学习内容资源！');
        resultArray = [];
    }
    return resultArray;
};

const encode = (datasource:string) => {
    try {
        const key = `${WXstate.KEY_DO}`;
      // DES requires the key to be exactly 8 bytes long
      const desKey = CryptoJS.enc.Utf8.parse(key.substring(0, 8)); // Truncate or use the first 8 characters of the key

      // Convert the datasource to a WordArray
      const data = CryptoJS.enc.Utf8.parse(datasource);

      // DES encryption
      const encrypted = CryptoJS.DES.encrypt(data, desKey, {
        mode: CryptoJS.mode.ECB, // Electronic Codebook mode
        padding: CryptoJS.pad.Pkcs7, // Padding scheme
      });

      // Return Base64 encoded ciphertext
      let st = encrypted.toString().replace(/=+$/, '');
      console.log(st);

      return st.replace(/[^A-Za-z0-9-]/g, '_');
    } catch (e) {
      console.error('Encryption error:', e);
      return 'null';
    }
  };

export default GetjsonData;
